import router from './router'
import store from './store'
import Router from 'vue-router'
import { message, Modal } from "ant-design-vue";
import { generator } from '@/utils/routerUtil'
import { SET_Ietype } from '@/store/modules/user'
// const whiteList = ['/login']

// 不需要登录拦截的路由配置
const loginIgnore = {
  names: ['404', '403', 'login', 'loginError', 'register', 'orgPageDemo', 'formDemo', 'forgePassword'],      //根据路由名称匹配
  paths: [],
  /**
   * 判断路由是否包含在该配置中
   * @param route vue-router 的 route 对象
   * @returns {boolean}
   */
  includes(route) {
    return this.names.includes(route.name) || this.paths.includes(route.path)
  }
}
// hack router push callback vue-router跳转相同路径报错
const originalPush = Router.prototype.push
Router.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

function getQueryVariable(variable) {
  let query = window.location.search.substring(1);
  let vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split("=");
    if (pair[0] === variable) { return pair[1]; }
  }
  return false;
}

if (getQueryVariable('accessToken')) {
  store.commit('SET_TOKEN', getQueryVariable('accessToken'))
}



let accessToken = store.state.user.accessToken;
if (accessToken) {
  let originRouters = store.state.user.originRouters;
  if (originRouters.length) {
    const rewriteRoutes = generator(originRouters);
    router.addRoutes(rewriteRoutes)
  }

}
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  if (to.path === '/login') {
    if (to.query.type == '1') {
      store.commit('SET_Ietype', '1')
    }
  }
  let accessToken = store.state.user.accessToken;
  let type=store.state.user.ietype;

  if (accessToken) {
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (type==1){
        store.commit('setMenuData', "")
        store.commit('SET_USER_INFO', "")
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => {
          store.dispatch('GetRouterMenu').then(routes => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(routes) // 动态添加可访问路由表
            // 初始化Admin后台菜单数据
            let menuRoutes = []
            routes.forEach((item) => {
              if (item.path === '/') {
                if (item.children) {
                  const data = item.children
                  menuRoutes = menuRoutes.concat(data)
                }
              }
            })
            if (menuRoutes) {
              store.dispatch('setMenuData', menuRoutes)
            }
            if(to.query && to.query.accessToken && to.query.redirect === 'false'){
              next({ path: to.path })
            }else {
              next({ path: '/' }) // hack方法 确保addRoutes已完成
            }
          })
        }
        ).catch(err => {
          Modal.confirm({
            title: '温馨提示',
            content: err.msg || err.message || '未获取到用户信息',
            cancelText: '关闭',
            okText: '确定',
            onOk() {
              store.commit('SET_TOKEN', "")
              store.commit('SET_Ietype', "")
            },
            onCancel() {
              store.commit('SET_TOKEN', "")
              store.commit('SET_Ietype', "")
            },
          });
        })
        store.commit('SET_Ietype', '2')
      }else {
      const userInfo = store.state.user.userInfo || {}
      if (userInfo.userName) {
        next()
      } else {
        // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => {
          store.dispatch('GetRouterMenu').then(routes => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(routes) // 动态添加可访问路由表
            // 初始化Admin后台菜单数据
            let menuRoutes = []
            routes.forEach((item) => {
              if (item.path === '/') {
                if (item.children) {
                  const data = item.children
                  menuRoutes = menuRoutes.concat(data)
                }
              }
            })
            if (menuRoutes) {
              store.dispatch('setMenuData', menuRoutes)
            }
            if(to.query && to.query.accessToken && to.query.redirect === 'false'){
              next({ path: to.path })
            }else {
              next({ path: '/' }) // hack方法 确保addRoutes已完成
            }
          })
        }).catch(err => {
          Modal.confirm({
            title: '温馨提示',
            content: err.msg || err.message || '未获取到用户信息',
            cancelText: '关闭',
            okText: '确定',
            onOk() {
              store.commit('SET_TOKEN', "")
            },
            onCancel() {
              store.commit('SET_TOKEN', "")
            },
          });
        })
      }
    }
    }
  } else {
    // 没有token
    if (loginIgnore.includes(to)) {
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    }
    // if (whiteList.indexOf(to.path) !== -1) {
    //   // 在免登录白名单，直接进入
    //   next()
    // } else {
    //   next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    // }
  }
})
